<?php

namespace app\webapi\vms\service;

use app\webapi\common\BaseService;
use app\webapi\vms\model\LinkModel;
use library\OWException;

/**
 * @链接服务类
 */
class LinkService extends BaseService
{
    /**
     * @desc 获取链接分页列表
     * @param $page_no
     * @param $page_size
     * @param $website_id
     * @param $type
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     * @author zhaozhiwei
     * @time 2023/12/14-11:54
     */
    public function getPaginateList($page_no, $page_size, $website_id, $type)
    {
        //定义查询参数
        $fields = ['id', 'name', 'url', 'type', 'sort', 'create_time'];
        //查询分页数据
        $where = ['type' => $type, 'website_id' => $website_id, 'delete_time' => 0];
        $list = LinkModel::field($fields)
            ->where($where)
            ->order('create_time','desc')
            ->paginate(['page' => $page_no, 'list_rows' => $page_size]);
        return $list;
    }

    /**
     * @desc 编辑链接（含新增）
     * @param $params
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/14-11:54
     */
    public function edit($params, $website_id)
    {
        $params['website_id'] = $website_id;
        //查询链接名称是否重复
        $model = (new LinkModel());
        $info = $model->where(['website_id' => $website_id, 'name' => $params['name']])->find();
        if (!empty($info)) {
            throw new OWException('链接名称重复');
        }
        if (isset($params['id']) && !empty($params['id']) && $params['id'] != '') {
            //编辑数据
            $model->where(['id' => $params['id']])->save($params);
        } else {
            //写入数据
            $model->save($params);
        }
        return true;
    }

    /**
     * @desc 获取链接信息详情
     * @param $id
     * @param $website_id
     * @return LinkModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/14-11:54
     */
    public function getInfo($id, $website_id)
    {
        $info = LinkModel::field(['id', 'name', 'url', 'type', 'sort', 'create_time'])->where(['id' => $id, 'website_id' => $website_id])->find();
        return $info;
    }

    /**
     * @desc 删除链接信息
     * @param $id_arr
     * @param $website_id
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/14-11:55
     */
    public function delete($id_arr, $website_id)
    {
        LinkModel::where(['id' => $id_arr, 'website_id' => $website_id])->update(['delete_time' => time()]);
        return true;
    }
}